package com.rickpan.service.impl;

import com.rickpan.dto.contacts.*;
import com.rickpan.dto.request.CreateFriendGroupRequest;
import com.rickpan.dto.response.FriendGroupResponse;
import com.rickpan.entity.*;
import com.rickpan.repository.*;
import com.rickpan.service.ContactService;
import com.rickpan.service.UserOnlineService;
import com.rickpan.socketio.TransferEventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 联系人服务实现类
 */
@Service
@Transactional
public class ContactServiceImpl implements ContactService {

    private static final Logger logger = LoggerFactory.getLogger(ContactServiceImpl.class);

    @Autowired
    private FriendRelationshipRepository friendRelationshipRepository;

    @Autowired
    private FriendRequestRepository friendRequestRepository;

    @Autowired
    private UserPrivacySettingsRepository privacySettingsRepository;

    @Autowired
    private UserOnlineStatusRepository onlineStatusRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private FriendGroupRepository friendGroupRepository;

    @Autowired
    @Lazy
    private TransferEventHandler transferEventHandler;

    @Autowired
    private UserOnlineService userOnlineService;

    // ==================== 好友关系管理 ====================

    @Override
    @Transactional(readOnly = true)
    public ContactsListResponse getFriendsList(Long userId, String group, String keyword) {
        logger.info("获取用户好友列表 userId={}, group={}, keyword={}", userId, group, keyword);

        List<FriendRelationship> relationships;
        
        // 根据条件查询好友关系
        if (StringUtils.hasText(keyword)) {
            relationships = friendRelationshipRepository.searchFriends(userId, keyword, FriendRelationship.Status.ACTIVE);
        } else if (StringUtils.hasText(group)) {
            relationships = friendRelationshipRepository.findByUserIdAndGroupNameAndStatus(userId, group, FriendRelationship.Status.ACTIVE);
        } else {
            relationships = friendRelationshipRepository.findByUserIdAndStatus(userId, FriendRelationship.Status.ACTIVE);
        }

        // 获取好友用户信息
        List<Long> friendIds = relationships.stream()
                .map(FriendRelationship::getFriendId)
                .collect(Collectors.toList());

        final Map<Long, User> friendsMap;
        if (!friendIds.isEmpty()) {
            List<User> friends = userRepository.findAllById(friendIds);
            friendsMap = friends.stream().collect(Collectors.toMap(User::getId, user -> user));
        } else {
            friendsMap = new HashMap<>();
        }

        // 获取在线状态
        final Map<Long, UserOnlineStatus> onlineStatusMap;
        if (!friendIds.isEmpty()) {
            List<UserOnlineStatus> onlineStatuses = onlineStatusRepository.findByUserIds(friendIds);
            onlineStatusMap = onlineStatuses.stream()
                    .collect(Collectors.toMap(UserOnlineStatus::getUserId, status -> status));
        } else {
            onlineStatusMap = new HashMap<>();
        }

        // 构建响应对象
        List<FriendResponse> friendResponses = relationships.stream()
                .map(relationship -> {
                    User friend = friendsMap.get(relationship.getFriendId());
                    UserOnlineStatus onlineStatus = onlineStatusMap.get(relationship.getFriendId());
                    return friend != null ? FriendResponse.from(relationship, friend, onlineStatus) : null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        // 获取分组列表
        List<String> groups = getFriendGroups(userId);

        // 统计信息
        long totalCount = friendResponses.size();
        long onlineCount = friendResponses.stream()
                .mapToLong(friend -> friend.getOnlineStatus() == UserOnlineStatus.Status.ONLINE ? 1 : 0)
                .sum();

        return ContactsListResponse.of(friendResponses, groups, totalCount, onlineCount);
    }

    @Override
    @Transactional(readOnly = true)
    public Page<FriendResponse> getFriendsPage(Long userId, String group, String keyword, Pageable pageable) {
        logger.info("获取用户好友列表（分页） userId={}, group={}, keyword={}, page={}", 
                   userId, group, keyword, pageable.getPageNumber());

        Page<FriendRelationship> relationshipsPage;
        
        // 根据条件查询好友关系（分页）
        if (StringUtils.hasText(group)) {
            relationshipsPage = friendRelationshipRepository.findByUserIdAndGroupNameAndStatus(
                    userId, group, FriendRelationship.Status.ACTIVE, pageable);
        } else {
            relationshipsPage = friendRelationshipRepository.findByUserIdAndStatus(
                    userId, FriendRelationship.Status.ACTIVE, pageable);
        }

        // 转换为响应对象
        List<FriendResponse> friendResponses = relationshipsPage.getContent().stream()
                .map(relationship -> {
                    User friend = userRepository.findById(relationship.getFriendId()).orElse(null);
                    UserOnlineStatus onlineStatus = onlineStatusRepository.findByUserId(relationship.getFriendId()).orElse(null);
                    return friend != null ? FriendResponse.from(relationship, friend, onlineStatus) : null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        return new PageImpl<>(friendResponses, pageable, relationshipsPage.getTotalElements());
    }

    @Override
    @Transactional(readOnly = true)
    public List<FriendResponse> getOnlineFriends(Long userId) {
        logger.info("获取用户在线好友 userId={}", userId);

        List<FriendRelationship> onlineRelationships = friendRelationshipRepository.findOnlineFriends(
                userId, FriendRelationship.Status.ACTIVE);

        return onlineRelationships.stream()
                .map(relationship -> {
                    User friend = userRepository.findById(relationship.getFriendId()).orElse(null);
                    UserOnlineStatus onlineStatus = onlineStatusRepository.findByUserId(relationship.getFriendId()).orElse(null);
                    return friend != null ? FriendResponse.from(relationship, friend, onlineStatus) : null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getFriendsOnlineStatus(Long userId) {
        logger.info("获取好友在线状态 userId={}", userId);

        try {
            // 1. 获取所有好友
            List<FriendRelationship> friendRelationships = friendRelationshipRepository
                    .findByUserIdAndStatus(userId, FriendRelationship.Status.ACTIVE);

            if (friendRelationships.isEmpty()) {
                return Map.of("friends", List.of(), "totalCount", 0, "onlineCount", 0);
            }

            // 2. 提取好友用户ID列表
            List<Long> friendUserIds = friendRelationships.stream()
                    .map(FriendRelationship::getFriendId)
                    .collect(Collectors.toList());

            // 3. 批量检查在线状态
            Map<Long, Boolean> onlineStatusMap = userOnlineService.batchCheckOnlineStatus(friendUserIds);

            // 4. 构建响应数据
            List<Map<String, Object>> friendsWithStatus = friendRelationships.stream()
                    .map(relationship -> {
                        Long friendUserId = relationship.getFriendId();
                        User friend = userRepository.findById(friendUserId).orElse(null);
                        if (friend == null) return null;

                        boolean isOnline = onlineStatusMap.getOrDefault(friendUserId, false);

                        Map<String, Object> friendData = new HashMap<>();
                        friendData.put("userId", friendUserId);
                        friendData.put("username", friend.getUsername());
                        friendData.put("realName", friend.getRealName());
                        friendData.put("isOnline", isOnline);
                        friendData.put("relationshipId", relationship.getId());
                        friendData.put("groupName", relationship.getGroupName());
                        friendData.put("remark", relationship.getRemark());

                        return friendData;
                    })
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            // 5. 统计在线数量
            long onlineCount = friendsWithStatus.stream()
                    .mapToLong(friend -> (Boolean) friend.get("isOnline") ? 1 : 0)
                    .sum();

            Map<String, Object> result = new HashMap<>();
            result.put("friends", friendsWithStatus);
            result.put("totalCount", friendsWithStatus.size());
            result.put("onlineCount", onlineCount);

            return result;

        } catch (Exception e) {
            logger.error("获取好友在线状态失败 userId={}", userId, e);
            return Map.of("friends", List.of(), "totalCount", 0, "onlineCount", 0);
        }
    }

    @Override
    public FriendResponse updateFriend(Long userId, Long relationshipId, UpdateFriendRequest request) {
        logger.info("更新好友信息 userId={}, relationshipId={}, request={}", userId, relationshipId, request);

        FriendRelationship relationship = friendRelationshipRepository.findById(relationshipId)
                .orElseThrow(() -> new RuntimeException("好友关系不存在"));

        // 验证权限
        if (!relationship.getUserId().equals(userId)) {
            throw new RuntimeException("无权限修改此好友关系");
        }

        // 更新信息
        if (StringUtils.hasText(request.getGroupName())) {
            relationship.setGroupName(request.getGroupName());
        }
        if (StringUtils.hasText(request.getRemark())) {
            relationship.setRemark(request.getRemark());
        }

        relationship = friendRelationshipRepository.save(relationship);

        // 获取好友信息和在线状态
        User friend = userRepository.findById(relationship.getFriendId())
                .orElseThrow(() -> new RuntimeException("好友用户不存在"));
        UserOnlineStatus onlineStatus = onlineStatusRepository.findByUserId(relationship.getFriendId()).orElse(null);

        return FriendResponse.from(relationship, friend, onlineStatus);
    }

    @Override
    public void deleteFriend(Long userId, Long relationshipId) {
        logger.info("删除好友关系 userId={}, relationshipId={}", userId, relationshipId);

        FriendRelationship relationship = friendRelationshipRepository.findById(relationshipId)
                .orElseThrow(() -> new RuntimeException("好友关系不存在"));

        // 验证权限
        if (!relationship.getUserId().equals(userId)) {
            throw new RuntimeException("无权限删除此好友关系");
        }

        // 删除双向好友关系
        friendRelationshipRepository.deleteByUserIdAndFriendId(userId, relationship.getFriendId());
        friendRelationshipRepository.deleteByUserIdAndFriendId(relationship.getFriendId(), userId);

        logger.info("已删除双向好友关系 userId1={}, userId2={}", userId, relationship.getFriendId());
    }

    @Override
    @Transactional(readOnly = true)
    public boolean areFriends(Long userId1, Long userId2) {
        return friendRelationshipRepository.existsFriendship(userId1, userId2, FriendRelationship.Status.ACTIVE);
    }

    @Override
    @Transactional(readOnly = true)
    public List<String> getFriendGroups(Long userId) {
        return friendRelationshipRepository.findDistinctGroupNamesByUserIdAndStatus(
                userId, FriendRelationship.Status.ACTIVE);
    }

    @Override
    @Transactional(readOnly = true)
    public List<FriendGroupResponse> getFriendGroupsDetail(Long userId) {
        logger.info("获取好友分组详细信息 userId={}", userId);

        try {
            // 1. 获取用户的所有分组
            List<FriendGroup> friendGroups = friendGroupRepository.findByUserIdOrderBySortOrderAscCreatedAtAsc(userId);

            // 2. 为每个分组计算好友数量
            List<FriendGroupResponse> responses = friendGroups.stream()
                    .map(group -> {
                        // 计算该分组下的好友数量
                        long friendCount = friendRelationshipRepository.countByUserIdAndGroupNameAndStatus(
                                userId, group.getGroupName(), FriendRelationship.Status.ACTIVE);

                        return FriendGroupResponse.from(group, friendCount);
                    })
                    .collect(Collectors.toList());

            logger.info("获取好友分组详细信息成功 userId={}, 分组数量={}", userId, responses.size());
            return responses;

        } catch (Exception e) {
            logger.error("获取好友分组详细信息失败 userId={}", userId, e);
            throw new RuntimeException("获取分组信息失败", e);
        }
    }

    @Override
    @Transactional
    public FriendGroupResponse createFriendGroup(Long userId, CreateFriendGroupRequest request) {
        logger.info("创建好友分组 userId={}, groupName={}", userId, request.getGroupName());

        try {
            // 1. 验证分组名称
            String groupName = request.getGroupName().trim();
            if (groupName.isEmpty()) {
                throw new RuntimeException("分组名称不能为空");
            }

            // 2. 检查分组是否已存在
            if (friendGroupRepository.existsByUserIdAndGroupName(userId, groupName)) {
                throw new RuntimeException("分组名称已存在");
            }

            // 3. 创建分组
            FriendGroup friendGroup = FriendGroup.builder()
                    .userId(userId)
                    .groupName(groupName)
                    .description(request.getDescription())
                    .sortOrder(request.getSortOrder() != null ? request.getSortOrder() : 0)
                    .build();

            FriendGroup savedGroup = friendGroupRepository.save(friendGroup);

            logger.info("好友分组创建成功 userId={}, groupId={}, groupName={}",
                    userId, savedGroup.getId(), savedGroup.getGroupName());

            return FriendGroupResponse.from(savedGroup, 0L);

        } catch (Exception e) {
            logger.error("创建好友分组失败 userId={}, groupName={}", userId, request.getGroupName(), e);
            throw new RuntimeException("创建分组失败: " + e.getMessage(), e);
        }
    }

    @Override
    @Transactional
    public void deleteFriendGroup(Long userId, Long groupId) {
        logger.info("删除好友分组 userId={}, groupId={}", userId, groupId);

        try {
            // 1. 查找分组
            Optional<FriendGroup> groupOpt = friendGroupRepository.findById(groupId);
            if (groupOpt.isEmpty()) {
                throw new RuntimeException("分组不存在");
            }

            FriendGroup group = groupOpt.get();

            // 2. 验证分组所有权
            if (!group.getUserId().equals(userId)) {
                throw new RuntimeException("无权限删除此分组");
            }

            // 3. 检查分组下是否有好友
            long friendCount = friendRelationshipRepository.countByUserIdAndGroupNameAndStatus(
                    userId, group.getGroupName(), FriendRelationship.Status.ACTIVE);

            if (friendCount > 0) {
                // 将该分组下的好友移动到默认分组
                friendRelationshipRepository.updateGroupNameByUserIdAndGroupName(
                        userId, group.getGroupName(), "默认分组");
                logger.info("已将分组 {} 下的 {} 个好友移动到默认分组", group.getGroupName(), friendCount);
            }

            // 4. 删除分组
            friendGroupRepository.delete(group);

            logger.info("好友分组删除成功 userId={}, groupId={}, groupName={}",
                    userId, groupId, group.getGroupName());

        } catch (Exception e) {
            logger.error("删除好友分组失败 userId={}, groupId={}", userId, groupId, e);
            throw new RuntimeException("删除分组失败: " + e.getMessage(), e);
        }
    }

    // ==================== 好友申请管理 ====================

    @Override
    public FriendRequestResponse sendFriendRequest(Long fromUserId, SendFriendRequestRequest request) {
        logger.info("发送好友申请 fromUserId={}, toUserId={}, message={}", 
                   fromUserId, request.getToUserId(), request.getMessage());

        Long toUserId = request.getToUserId();

        // 验证基本条件
        if (fromUserId.equals(toUserId)) {
            throw new RuntimeException("不能添加自己为好友");
        }

        // 检查目标用户是否存在
        User toUser = userRepository.findById(toUserId)
                .orElseThrow(() -> new RuntimeException("目标用户不存在"));

        // 检查是否已经是好友
        if (areFriends(fromUserId, toUserId)) {
            throw new RuntimeException("已经是好友关系");
        }

        // 检查是否可以发送申请
        if (!canSendFriendRequest(fromUserId, toUserId)) {
            throw new RuntimeException("无法发送好友申请，可能已存在待处理的申请");
        }

        // 检查目标用户的隐私设置
        UserPrivacySettings privacySettings = privacySettingsRepository.findByUserId(toUserId).orElse(null);
        if (privacySettings != null && !privacySettings.canReceiveFriendRequest()) {
            throw new RuntimeException("目标用户不接受好友申请");
        }

        // 创建好友申请
        FriendRequest friendRequest = new FriendRequest(fromUserId, toUserId, request.getMessage());
        friendRequest = friendRequestRepository.save(friendRequest);

        // 获取用户信息
        User fromUser = userRepository.findById(fromUserId)
                .orElseThrow(() -> new RuntimeException("申请人用户不存在"));

        // 创建响应对象
        FriendRequestResponse response = FriendRequestResponse.from(friendRequest, fromUser, toUser);

        // 发送Socket.IO通知
        transferEventHandler.sendFriendRequestNotification(toUserId, response);

        logger.info("好友申请已发送 requestId={}", friendRequest.getId());
        return response;
    }

    @Override
    public FriendRequestResponse handleFriendRequest(Long userId, Long requestId, HandleFriendRequestRequest request) {
        logger.info("处理好友申请 userId={}, requestId={}, action={}", userId, requestId, request.getAction());

        FriendRequest friendRequest = friendRequestRepository.findById(requestId)
                .orElseThrow(() -> new RuntimeException("好友申请不存在"));

        // 验证权限
        if (!friendRequest.getToUserId().equals(userId)) {
            throw new RuntimeException("无权限处理此好友申请");
        }

        // 检查申请状态
        if (!friendRequest.isPending()) {
            throw new RuntimeException("申请已处理或已过期");
        }

        // 处理申请
        if (request.getAction() == HandleFriendRequestRequest.Action.ACCEPT) {
            // 接受申请
            friendRequest.accept(request.getResponseMessage());

            // 创建双向好友关系
            FriendRelationship relationship1 = new FriendRelationship(friendRequest.getFromUserId(), friendRequest.getToUserId());
            FriendRelationship relationship2 = new FriendRelationship(friendRequest.getToUserId(), friendRequest.getFromUserId());

            friendRelationshipRepository.save(relationship1);
            friendRelationshipRepository.save(relationship2);

            logger.info("好友申请已接受，创建双向好友关系 userId1={}, userId2={}",
                       friendRequest.getFromUserId(), friendRequest.getToUserId());
        } else {
            // 拒绝申请
            friendRequest.reject(request.getResponseMessage());
            logger.info("好友申请已拒绝 requestId={}", requestId);
        }

        friendRequest = friendRequestRepository.save(friendRequest);

        // 获取用户信息
        User fromUser = userRepository.findById(friendRequest.getFromUserId())
                .orElseThrow(() -> new RuntimeException("申请人用户不存在"));
        User toUser = userRepository.findById(friendRequest.getToUserId())
                .orElseThrow(() -> new RuntimeException("目标用户不存在"));

        // 创建响应对象
        FriendRequestResponse response = FriendRequestResponse.from(friendRequest, fromUser, toUser);

        // 发送Socket.IO通知给申请人
        transferEventHandler.sendFriendRequestResponseNotification(friendRequest.getFromUserId(), response);

        return response;
    }

    @Override
    @Transactional(readOnly = true)
    public Page<FriendRequestResponse> getReceivedRequests(Long userId, FriendRequest.Status status, Pageable pageable) {
        logger.info("获取收到的好友申请 userId={}, status={}", userId, status);

        Page<FriendRequest> requestsPage;
        if (status != null) {
            requestsPage = friendRequestRepository.findByToUserIdAndStatus(userId, status, pageable);
        } else {
            requestsPage = friendRequestRepository.findByToUserIdOrderByCreatedAtDesc(userId)
                    .stream()
                    .collect(Collectors.collectingAndThen(
                            Collectors.toList(),
                            list -> new PageImpl<>(
                                    list.subList(
                                            Math.min((int) pageable.getOffset(), list.size()),
                                            Math.min((int) (pageable.getOffset() + pageable.getPageSize()), list.size())
                                    ),
                                    pageable,
                                    list.size()
                            )
                    ));
        }

        List<FriendRequestResponse> responses = requestsPage.getContent().stream()
                .map(request -> {
                    User fromUser = userRepository.findById(request.getFromUserId()).orElse(null);
                    User toUser = userRepository.findById(request.getToUserId()).orElse(null);
                    return (fromUser != null && toUser != null) ?
                            FriendRequestResponse.from(request, fromUser, toUser) : null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        return new PageImpl<>(responses, pageable, requestsPage.getTotalElements());
    }

    @Override
    @Transactional(readOnly = true)
    public Page<FriendRequestResponse> getSentRequests(Long userId, FriendRequest.Status status, Pageable pageable) {
        logger.info("获取发送的好友申请 userId={}, status={}", userId, status);

        Page<FriendRequest> requestsPage;
        if (status != null) {
            requestsPage = friendRequestRepository.findByFromUserIdAndStatus(userId, status, pageable);
        } else {
            requestsPage = friendRequestRepository.findByFromUserIdOrderByCreatedAtDesc(userId)
                    .stream()
                    .collect(Collectors.collectingAndThen(
                            Collectors.toList(),
                            list -> new PageImpl<>(
                                    list.subList(
                                            Math.min((int) pageable.getOffset(), list.size()),
                                            Math.min((int) (pageable.getOffset() + pageable.getPageSize()), list.size())
                                    ),
                                    pageable,
                                    list.size()
                            )
                    ));
        }

        List<FriendRequestResponse> responses = requestsPage.getContent().stream()
                .map(request -> {
                    User fromUser = userRepository.findById(request.getFromUserId()).orElse(null);
                    User toUser = userRepository.findById(request.getToUserId()).orElse(null);
                    return (fromUser != null && toUser != null) ?
                            FriendRequestResponse.from(request, fromUser, toUser) : null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        return new PageImpl<>(responses, pageable, requestsPage.getTotalElements());
    }

    @Override
    @Transactional(readOnly = true)
    public long getPendingRequestsCount(Long userId) {
        return friendRequestRepository.countByToUserIdAndStatus(userId, FriendRequest.Status.PENDING);
    }

    @Override
    @Transactional(readOnly = true)
    public boolean canSendFriendRequest(Long fromUserId, Long toUserId) {
        return friendRequestRepository.canSendFriendRequest(fromUserId, toUserId);
    }

    // ==================== 用户搜索 ====================

    @Override
    @Transactional(readOnly = true)
    public Page<UserSearchResponse> searchUsers(Long currentUserId, UserSearchRequest request) {
        logger.info("搜索用户 currentUserId={}, keyword={}, searchType={}",
                   currentUserId, request.getKeyword(), request.getSearchType());

        // 构建搜索条件
        String keyword = request.getKeyword().trim();
        UserSearchRequest.SearchType searchType = request.getSearchType();

        // 根据搜索类型查找用户
        List<User> users = searchUsersByType(keyword, searchType);

        // 过滤掉当前用户自己
        users = users.stream()
                .filter(user -> !user.getId().equals(currentUserId))
                .collect(Collectors.toList());

        // 如果需要排除已有好友
        if (request.getExcludeFriends()) {
            Set<Long> friendIds = friendRelationshipRepository.findByUserIdAndStatus(
                    currentUserId, FriendRelationship.Status.ACTIVE)
                    .stream()
                    .map(FriendRelationship::getFriendId)
                    .collect(Collectors.toSet());

            users = users.stream()
                    .filter(user -> !friendIds.contains(user.getId()))
                    .collect(Collectors.toList());
        }

        // 检查隐私设置过滤
        users = filterUsersByPrivacySettings(users, searchType);

        // 分页处理
        int start = request.getPage() * request.getSize();
        int end = Math.min(start + request.getSize(), users.size());
        List<User> pagedUsers = users.subList(start, end);

        // 构建响应对象
        List<UserSearchResponse> responses = pagedUsers.stream()
                .map(user -> {
                    UserSearchResponse response = UserSearchResponse.from(user);

                    // 设置好友关系状态
                    response.setIsFriend(areFriends(currentUserId, user.getId()));

                    // 检查是否有待处理的申请
                    boolean hasPendingRequest = friendRequestRepository.findBidirectionalRequests(
                            currentUserId, user.getId(), FriendRequest.Status.PENDING).size() > 0;
                    response.setHasPendingRequest(hasPendingRequest);

                    // 检查是否可以发送申请
                    response.setCanSendRequest(canSendFriendRequest(currentUserId, user.getId()));

                    return response;
                })
                .collect(Collectors.toList());

        return new PageImpl<>(responses,
                org.springframework.data.domain.PageRequest.of(request.getPage(), request.getSize()),
                users.size());
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<UserSearchResponse> findUserByUsername(Long currentUserId, String username) {
        logger.info("根据用户名查找用户 currentUserId={}, username={}", currentUserId, username);

        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isEmpty()) {
            return Optional.empty();
        }

        User user = userOpt.get();

        // 检查隐私设置
        UserPrivacySettings privacySettings = privacySettingsRepository.findByUserId(user.getId()).orElse(null);
        if (privacySettings != null && !privacySettings.canBeSearchedBy("USERNAME")) {
            return Optional.empty();
        }

        UserSearchResponse response = UserSearchResponse.from(user);
        response.setIsFriend(areFriends(currentUserId, user.getId()));

        boolean hasPendingRequest = friendRequestRepository.findBidirectionalRequests(
                currentUserId, user.getId(), FriendRequest.Status.PENDING).size() > 0;
        response.setHasPendingRequest(hasPendingRequest);
        response.setCanSendRequest(canSendFriendRequest(currentUserId, user.getId()));

        return Optional.of(response);
    }

    private List<User> searchUsersByType(String keyword, UserSearchRequest.SearchType searchType) {
        switch (searchType) {
            case USERNAME:
                return userRepository.findByUsernameContainingIgnoreCase(keyword);
            case EMAIL:
                return userRepository.findByEmailContainingIgnoreCase(keyword);
            case REAL_NAME:
                return userRepository.findByRealNameContainingIgnoreCase(keyword);
            case ALL:
            default:
                // 搜索所有类型
                Set<User> allUsers = new HashSet<>();
                allUsers.addAll(userRepository.findByUsernameContainingIgnoreCase(keyword));
                allUsers.addAll(userRepository.findByEmailContainingIgnoreCase(keyword));
                allUsers.addAll(userRepository.findByRealNameContainingIgnoreCase(keyword));
                return new ArrayList<>(allUsers);
        }
    }

    private List<User> filterUsersByPrivacySettings(List<User> users, UserSearchRequest.SearchType searchType) {
        return users.stream()
                .filter(user -> {
                    UserPrivacySettings settings = privacySettingsRepository.findByUserId(user.getId()).orElse(null);
                    if (settings == null) {
                        return true; // 没有隐私设置，默认允许搜索
                    }

                    switch (searchType) {
                        case USERNAME:
                            return settings.getAllowSearchByUsername();
                        case EMAIL:
                            return settings.getAllowSearchByEmail();
                        case REAL_NAME:
                            return settings.getAllowSearchByRealName();
                        case ALL:
                        default:
                            // 对于全部搜索，只要有一种方式允许就可以
                            return settings.getAllowSearchByUsername() ||
                                   settings.getAllowSearchByEmail() ||
                                   settings.getAllowSearchByRealName();
                    }
                })
                .collect(Collectors.toList());
    }

    // ==================== 隐私设置管理 ====================

    @Override
    @Transactional
    public PrivacySettingsResponse getPrivacySettings(Long userId) {
        logger.info("获取用户隐私设置 userId={}", userId);

        UserPrivacySettings settings = privacySettingsRepository.findByUserId(userId)
                .orElseGet(() -> initializeDefaultPrivacySettings(userId));

        return PrivacySettingsResponse.from(settings);
    }

    @Override
    public PrivacySettingsResponse updatePrivacySettings(Long userId, UpdatePrivacySettingsRequest request) {
        logger.info("更新用户隐私设置 userId={}, request={}", userId, request);

        UserPrivacySettings settings = privacySettingsRepository.findByUserId(userId)
                .orElseGet(() -> new UserPrivacySettings(userId));

        // 更新设置
        settings.setAllowSearchByUsername(request.getAllowSearchByUsername());
        settings.setAllowSearchByEmail(request.getAllowSearchByEmail());
        settings.setAllowSearchByRealName(request.getAllowSearchByRealName());
        settings.setShowOnlineStatus(request.getShowOnlineStatus());
        settings.setAllowFriendRequests(request.getAllowFriendRequests());
        settings.setAutoAcceptTeamMembers(request.getAutoAcceptTeamMembers());

        settings = privacySettingsRepository.save(settings);

        logger.info("隐私设置已更新 userId={}", userId);
        return PrivacySettingsResponse.from(settings);
    }

    @Override
    public UserPrivacySettings initializeDefaultPrivacySettings(Long userId) {
        logger.info("初始化用户默认隐私设置 userId={}", userId);

        UserPrivacySettings settings = new UserPrivacySettings(userId);
        return privacySettingsRepository.save(settings);
    }

    // ==================== 业务辅助方法 ====================

    @Override
    public int cleanupExpiredRequests() {
        logger.info("清理过期的好友申请");

        int cleanedCount = friendRequestRepository.markExpiredRequests(LocalDateTime.now());

        logger.info("已清理过期好友申请 count={}", cleanedCount);
        return cleanedCount;
    }

    @Override
    @Transactional(readOnly = true)
    public ContactsStatistics getFriendsStatistics(Long userId) {
        logger.info("获取用户好友统计信息 userId={}", userId);

        long totalFriends = friendRelationshipRepository.countByUserIdAndStatus(userId, FriendRelationship.Status.ACTIVE);

        List<FriendRelationship> onlineRelationships = friendRelationshipRepository.findOnlineFriends(
                userId, FriendRelationship.Status.ACTIVE);
        long onlineFriends = onlineRelationships.size();

        long pendingRequests = friendRequestRepository.countByToUserIdAndStatus(userId, FriendRequest.Status.PENDING);
        long sentRequests = friendRequestRepository.countByFromUserIdAndStatus(userId, FriendRequest.Status.PENDING);

        return new ContactsStatistics(totalFriends, onlineFriends, pendingRequests, sentRequests);
    }
}
